package com.jh.paymentchannel.service;

import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.pojo.BranchNo;
import com.jh.paymentchannel.util.Util;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class YHTopupRequest implements TopupRequest {

	private static final Logger log = LoggerFactory.getLogger(YHTopupRequest.class);

	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;

	@Autowired
	private BranchbankBussiness branchbankBussiness;

	@Autowired
	private Util util;

	@Value("${payment.ipAddress}")
	private String ipAddress;

	// 商户编号
	@Value("${yh.org_no}")
	private String orgNo;

	// 秘钥
	@Value("${yh.key}")
	private String Key;

	// 支付申请地址
	@Value("${yh.payApplyUrl}")
	private String payApplyUrl;

	private static final Charset UTF_8 = StandardCharsets.UTF_8;

	@Override
	public Map<String, String> topupRequest(HttpServletRequest request, String amount, String ordercode,
			String orderdesc, String extra, String notifyurl, String returnurl, String channelParam) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		/** 首先拿到用户的userid, 如果用户已经存在，那么直接拿用户的sdjuserid, 如果用户的默认结算卡已经和当前不一样了。 需要重新注册 **/
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "yh");
			map.put("resp_message", "没有该订单信息");
			return map;
		}

		String realamount = resultObj.getString("realAmount");
		String userid = resultObj.getString("userid");
		// 通道id
		String channelid = resultObj.getString("channelid");
		// 费率
		String rate = resultObj.getString("rate");
		// 银行卡(支付卡)
		String bankCard = resultObj.getString("bankcard");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "yh");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}

		if (resultObj.isNullObject()) {

			map.put("resp_code", "failed");
			map.put("channel_type", "yh");
			map.put("resp_message", "没有结算卡");
			return map;
		}
		//结算卡卡号
		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		/** 身份证号 */
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		// 开户行所在省
		String provinceOfBank = resultObj.getString("province");

//		System.out.println("provinceOfBank" + provinceOfBank);
		// 开户行所在市
		String cityOfBank = resultObj.getString("city");

//		System.out.println("cityOfBank" + cityOfBank);
		// 银行名称
		String bankName = resultObj.getString("bankName");
		// 支行名称
		String bankBranchName = resultObj.getString("bankBranchName");

		String expiredTime = resultObj.getString("expiredTime");

		String securityCode = resultObj.getString("securityCode");

		String cardType = resultObj.getString("cardType");

		String bankBranchNo;
		try {
			bankBranchNo = branchbankBussiness.getNumByName(bankBranchName);
		} catch (Exception e1) {
			map.put("resp_code", "failed");
			map.put("channel_type", "yh");
			map.put("resp_message", "查询支行联行号有误");
			return map;
		}
//		System.out.println("bankBranchNo" + bankBranchNo);

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "yh");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		if (resultObj == null) {
			return null;
		}

		String cardName = resultObj.getString("bankName");

		String bankname = Util.queryBankNameByBranchName(bankName);
		String cardname = Util.queryBankNameByBranchName(cardName);
		
		//交通银行的信用卡单笔不能超过 5000元
		if(cardname.contains("交通银行")){
			String money = "5000";
			
			BigDecimal bigAmount = new BigDecimal(amount);
			BigDecimal bigMoney = new BigDecimal(money);
			
			int compareTo = bigAmount.compareTo(bigMoney);
			
			if(compareTo>0){
				map.put("resp_code", "failed");
				map.put("channel_type", "yh");
				map.put("resp_message", "亲,交通银行的信用卡单笔不能超过 5000 元哦");
				return map;
			}
		}
		
		// 根据银行名称查询得到银行信息
		BranchNo findByBankName;
		try {
			findByBankName = branchbankBussiness.findByBankName(bankname);
		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "yh");
			map.put("resp_message", "查询银行信息有误");
			return map;
		}
		// 银行总行联行号
		String inBankUnitNo = findByBankName.getBankNo();

		if (provinceOfBank == null || "".equals(provinceOfBank) || "null".equals(provinceOfBank)) {
			provinceOfBank = "";
		}

		if (cityOfBank == null || "".equals(cityOfBank) || "null".equals(cityOfBank)) {
			cityOfBank = "";
		}

		if (bankBranchNo == null || "".equals(bankBranchNo) || "".equals(bankBranchNo)) {
			bankBranchNo = "";
		}

		if (bankBranchName == null || "".equals(bankBranchName) || "null".equals(bankBranchName)) {
			bankBranchName = "";
		}

		Map maps = new HashMap();
		maps.put("resp_code", "success");
		maps.put("channel_type", "yh");
		maps.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/toyhbankinfo?bankName="
				+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo=" + cardNo
				+ "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8") + "&amount=" + amount
				+ "&ordercode=" + ordercode + "&provinceOfBank=" + URLEncoder.encode(provinceOfBank, "UTF-8")
				+ "&cityOfBank=" + URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
				+ URLEncoder.encode(bankBranchName, "UTF-8"));
		return maps;

	}

}
